package com.ly.hotel.spainterface.jg.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jg.JgActivity;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.MassageItemBean;
import com.ly.hotel.spainterface.jg.bean.OnAddToBasketCompleted;
import com.ly.hotel.spainterface.jg.utils.AvoidDoubleClickedUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by ThinkPad on 2018/2/8.
 * 商品下单、处理、呼叫服务员界面
 */

public class CustomBuyGoodsDialogFragment extends DialogFragment {

    private ImageView goodsImage;
    private BitmapTask task;
    private int orderNum = 1;
    private OnAddToBasketCompleted onAddToBasketCompleted;
    private List<MassageItem> massageItems;
    private MyApplication app;

    public void setOnAddToBasketCompleted(OnAddToBasketCompleted onAddToBasketCompleted){
        this.onAddToBasketCompleted = onAddToBasketCompleted;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
        app = new MyApplication();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 设置Dialog宽度占比为50%，高度为wrap_content
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.5), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        /*layoutParams.gravity = Gravity.BOTTOM;
        layoutParams.y = 30;*/
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// 设置背景半透明
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置无标题
        View view = inflater.inflate(R.layout.jg_buy_goods_layout,container,false);

        ImageButton goodsOrderClose =  view.findViewById(R.id.goods_order_close);
        TextView goodsPrice = view.findViewById(R.id.goods_price);
        TextView goodsName =  view.findViewById(R.id.goods_name);
        final TextView goodsNum = view.findViewById(R.id.goods_num);

        Button goodsAdd = view.findViewById(R.id.goods_add);
        Button goodsSub = view.findViewById(R.id.goods_sub);
        goodsImage = view.findViewById(R.id.goods_image);

        Button goodsOrder = view.findViewById(R.id.goods_order);
        final Button callWaiter = view.findViewById(R.id.call_waiter);
        Button addToBasket = view.findViewById(R.id.add_to_basket);

        // 获取的Activity传递过来的数据
        Bundle bundle = getArguments();
        final String cashierIP = bundle.getString("cashierIP");
        final String cashierPORT = bundle.getString("cashierPORT");
        final String tvName = bundle.getString("tvName");
        final String categoryName = bundle.getString("categoryName");
        final MassageItemBean massageItemBean = (MassageItemBean) bundle.getSerializable("massageItemBean");
        final MassageItem massageItem = massageItemBean.getMassageItem();
        final int limitedGoodsNum = bundle.getInt("limitedGoodsNum");
        final boolean isOnlySee = bundle.getBoolean("isOnlySee");

        String massageItemName = massageItem.getName();
        String massageItemUnit = massageItem.getUnit();
        double massageItemPrice = massageItem.getPrice();
        int num = massageItem.getNum();
        Log.d("JgMainActivity","num=" + num);
        if(num > 0){
            //massageItem.setNum(num);
            orderNum = num;
        }else{
            massageItem.setNum(orderNum);// 设置商品的数量
        }

        String imageUrl = bundle.getString("imageUrl");

        setImageView(imageUrl);
        goodsPrice.setText("￥" + massageItemPrice + "元/" + massageItemUnit);
        goodsName.setText(massageItemName);
        goodsNum.setText(orderNum + "");

        // 监听关闭按钮
        goodsOrderClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                task.cancel(false);// 关闭窗口时，取消还在执行的加载图片异步任务
                dismiss();
            }
        });

        // 监听增加购买数量按钮
        goodsAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(limitedGoodsNum == 0){ //为0的时候表明，没有对购买商品数量进行限制
                    orderNum ++;
                    goodsNum.setText(orderNum + "");
                }else{
                    if(orderNum < limitedGoodsNum){
                        orderNum ++;
                        goodsNum.setText(orderNum + "");
                    }else{
                        Toast.makeText(MyApplication.getContext(),"购买的商品数量不能高于" + limitedGoodsNum,Toast.LENGTH_SHORT).show();
                    }
                }
                //massageItem.setNum(orderNum);
            }
        });

        // 监听减少购买数量按钮
        goodsSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(orderNum > 1){
                    orderNum --;
                    goodsNum.setText(orderNum + "");
                }else{
                    Toast.makeText(MyApplication.getContext(),"购买的商品数量不能低于" + orderNum,Toast.LENGTH_SHORT).show();
                }
                //massageItem.setNum(orderNum);
            }
        });

        // 添加商品到购物篮中
        addToBasket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isOnlySee){
                    CustomToast customToast = CustomToast.makeText(getActivity(),"暂无法添加商品到购物篮！",Toast.LENGTH_SHORT,false);
                    customToast.setGravity(Gravity.CENTER,0,0);
                    customToast.show();
                }else{
                    massageItem.setNum(orderNum);
                    onAddToBasketCompleted.addToBasketCompleted(massageItem,orderNum);
                    dismiss();
                }
            }
        });

        // 立即下单
        goodsOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒
                    return;
                }
                if(isOnlySee){
                    CustomToast customToast = CustomToast.makeText(getActivity(),"暂无法下单，请呼叫服务员下单！",Toast.LENGTH_SHORT,false);
                    customToast.setGravity(Gravity.CENTER,0,0);
                    customToast.show();
                }else{
                    CustomOrderDialog customOrderDialog = new CustomOrderDialog();
                    customOrderDialog.setCancelable(false);
                    Bundle bundle = new Bundle();
                    bundle.putString("cashierIP",cashierIP);
                    bundle.putString("cashierPORT",cashierPORT);
                    bundle.putString("tvName",tvName);
                    bundle.putString("categoryName",categoryName);
                    bundle.putSerializable("massageItemBean",massageItemBean);
                    bundle.putInt("orderNum",orderNum);
                    customOrderDialog.setArguments(bundle);
                    customOrderDialog.show(getFragmentManager(),"CustomOrderDialog");
                    dismiss();
                }
            }
        });

        // 呼叫服务员
        callWaiter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒
                    return;
                }
                // 呼叫服务员
                ((JgActivity)getActivity()).call();
            }
        });
        return view;
    }

    public void setImageView(String imageUrl){
        task = new BitmapTask();
        task.execute(imageUrl);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(task != null && task.getStatus() == AsyncTask.Status.RUNNING){
            task.cancel(true);
        }
    }

    class BitmapTask extends AsyncTask<String,Void,Bitmap>{

        private String imageUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadBitmap(imageUrl);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(bitmap == null){
                goodsImage.setImageResource(R.mipmap.jg_massage_item_default);
            }else{
                goodsImage.setImageBitmap(bitmap);
            }
        }

        private Bitmap downloadBitmap(String imageUrl){
            InputStream is = OkHttpUtils.getInstance().getImageResource(imageUrl);
            Bitmap bitmap = null;
            if(is != null){
                bitmap = decodeSampleBitmapFromStream(is,150,135);
            }
            return bitmap;
        }
    }

    // 将字节流转换为Bitmap对象
    public static Bitmap decodeSampleBitmapFromStream(InputStream is, int reqWidth, int reqHeight){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 设置为true，系统不会分配内存
        byte[] data = inputStreamToByteArray(is);
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = caculateInSampleSize(options,reqWidth,reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        return bitmap;
    }

    //计算inSampleSize值,reqWidth为ImageView要求的宽度
    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeigh){
        // 获得资源图片的宽度和高度
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if(width > reqWidth || height >reqHeigh){
            // 计算出资源图片和目标图片之间的比例
            final int heightRadio = Math.round((float) height / (float) reqHeigh);
            final int widthRadio = Math.round((float) width / (float) reqWidth);
            // 选择比例最小的作为inSampleSzie值
            inSampleSize = heightRadio < widthRadio ? heightRadio : widthRadio;
        }
        return inSampleSize;
    }

    // 将字节流转化为字节数组
    public static byte[] inputStreamToByteArray(InputStream inputStream) {
        try{
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ( (len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return outputStream.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
